//
//  ConfirmViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/18.
//  Copyright © 2016年 Jack. All rights reserved.
//   确认订单

#import "ConfirmViewController.h"
#import "HeaderFileForEasyToTesco.h"


#import "OrderDetailTableViewCell.h"
#import "OrderPayTableViewCell.h"
#import "ConfirmOrderNumTableViewCell.h"
//beizhu
#import "TextfeildTableViewCell.h"


#import "UIImageView+WebCache.h"
#import "AFNetworking.h"


//订单支付
#import "OrderPayViewController.h"
#import "ConfirmTableViewCell.h"

//获取收货地址
#import "GetAddressViewController.h"

#import "qqTableViewCell.h"
#import "ReadLoginData.h"

#import "AddAddressViewController.h"
#import "ManagerViewController.h"
#import "GetAddressViewController.h"



@interface ConfirmViewController ()<UITableViewDataSource, UITableViewDelegate, ConfirmOrderNumTableViewCelldelegate,UIAlertViewDelegate>



{
    NSInteger orderstate;
    BOOL BtnState;
    NSString *usernameStr;
    BOOL address;
}

@property (nonatomic, strong)UITableView *confirmtableview;
@property (nonatomic, strong) UILabel *Allprice;
@property (nonatomic, copy)NSString *name;
@property (nonatomic, copy)NSString *phone;
@property (nonatomic, copy)NSString *address;
@property (nonatomic, strong)NSDictionary *dic;
@property(nonatomic,copy)NSString *payAllMoney;


//收货数组
@property (nonatomic, strong)NSDictionary *addressDict;

@end

@implementation ConfirmViewController

- (NSDictionary *)addressDict
{
    if (_addressDict == nil) {
        _addressDict = [NSDictionary dictionary];
    }
    return _addressDict;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressNotification:) name:ShopCarGetAddressNotification object:nil];
}
- (void)addressNotification:(NSNotification *)noti{
    self.addressDict = noti.userInfo;
    address = YES;
    [self.confirmtableview reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self getdata];
    [self addconfirminitsth];
   
    [self addconfirmtopviewUI];
    
    [self addconfirmtableviewUI];
    //加载底部视图
    [self addconfirmlastviewlUI];
    
    
}

- (void)addconfirminitsth {
//    goodsNum = [self.confirmDic[@"goodsCount"] integerValue];
//    price = self.confirmDic[@"huiyuanjia"];
}

- (void)addconfirmtopviewUI {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"确认订单";
    

}
- (void)textField:(NSDictionary *)sender{
    
    self.name = sender[@"name"];

    NSLog(@"self.name%@",self.dic);
    
}
- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)addconfirmtableviewUI {
    self.confirmtableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.83) style:UITableViewStylePlain];
    self.confirmtableview.delegate = self;
    self.confirmtableview.dataSource = self;
    self.confirmtableview.tableFooterView =[[UIView alloc] init];
    self.confirmtableview.backgroundColor = [UIColor colorWithRed:244/255. green:244/255. blue:244/255. alpha:1];
    [self.view addSubview:self.confirmtableview];
    
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return self.goodsInfoArrM.count;
    } else if (section == 4) {
        return 0;
    } else if (section == 3) {
        return 2;
    } else {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        //显示收货地址
//        static NSString *identifier = @"OrderDetailTableViewCell1";
        qqTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qqtabeviecel"];
        
        if (cell == nil) {

            cell = [[qqTableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"qqtabeviecel"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        if (address == YES) {
            cell.Name.text = self.addressDict[@"name"];
            cell.PhoneNum.text = self.addressDict[@"phone"];
            cell.Address.text = [NSString stringWithFormat:@"%@%@%@%@",self.addressDict[@"province"],self.addressDict[@"city"],self.addressDict[@"county"],self.addressDict[@"address"]];

        }else {
            
            cell.Name.text = @"";
            cell.PhoneNum.text = @"";
            cell.Address.text = @"";
        }

//
//        cell.Name.text = self.wholeAddArray[0][@"name"];
        //            cell.PhoneNum.text = self.wholeAddArray[0][@"phone"];
        //            cell.Address.text = [NSString stringWithFormat:@"%@%@%@%@",self.wholeAddArray[0][@"province"],self.wholeAddArray[0][@"city"],self.wholeAddArray[0][@"county"],self.wholeAddArray[0][@"address"]];
        //            [self.confirmtableview reloadData];
        return cell;
        
    } else if (indexPath.section == 1) {
        static NSString *identifier = @"ConfirmTableViewCell";
        ConfirmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ConfirmTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        NSString *str1 = self.goodsInfoArrM[indexPath.row][@"picurl"];
        NSString *str2 = @"aaaa";
        if (self.picNameNum == 0) {
            str2 = self.goodsInfoArrM[indexPath.row][@"picprex"][@"s"];
        } else {
            str2 = self.goodsInfoArrM[indexPath.row][@"picprex"][@"picurl"];
        }
        NSString *str3 = [str2 stringByAppendingString:str1];
        [cell.ConfirmPicImage sd_setImageWithURL:[NSURL URLWithString:str3]];
        cell.ConfirmTitleLabel.text = [NSString stringWithFormat:@"%@", self.goodsInfoArrM[indexPath.row][@"title"]];
        cell.confirmMoneylabel.text = [NSString stringWithFormat:@"%.0f积分", self.allPrice];
        
        cell.yunfeiLabel.text = [NSString stringWithFormat:@"运费:%@积分", self.goodsInfoArrM[indexPath.row][@"jzh"]];
//        self.allYunFei = self.allYunFei + [self.goodsInfoArrM[indexPath.row][@"jzh"] intValue];
        
        int num = [self.goodsInfoArrM[indexPath.row][@"feilv"] intValue];
        if (num != 0) {
            cell.rateLabel.text = [NSString stringWithFormat:@"费率:%@%%", self.goodsInfoArrM[indexPath.row][@"feilv"]];
            NSLog(@"%d-----%d------%d", [self.goodsInfoArrM[indexPath.row][@"jiage"] intValue], [self.goodsInfoArrM[indexPath.row][@"feilv"] intValue], [self.goodsInfoArrM[indexPath.row][@"nums"] intValue]);

            NSLog(@"%f", self.allRate);

            
        } else {
            cell.rateLabel.text = @"";
        }
        if (self.picNameNum == 0) {
            cell.ConfirmNumLabel.text = [NSString stringWithFormat:@"x%@", self.goodsInfoArrM[indexPath.row][@"nums"]];
        } else {
            cell.ConfirmNumLabel.text = [NSString stringWithFormat:@"×%d", self.num];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if (indexPath.section == 2) {
        if (indexPath.row == 4){
            static NSString *identifier = @"TextfeildTableViewCell";
        TextfeildTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"TextfeildTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        }
            return cell;
        }else {
            static NSString *identifier = @"zanding1";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.textLabel.text = @"配送方式";
            cell.detailTextLabel.text= @"快递 ";
            
            return cell;
        }
    } else {
        static NSString *identifier = @"zanding2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = @"费率";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"+%.2f", self.allRate];
        } else {
            cell.textLabel.text = @"运费";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"+%d", self.allYunFei];
        }
        return cell;
    }
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 110;
    } else if (indexPath.section == 1) {
        return 110;
        
    }else {
        return 60;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 4 || section == 3) {
        return 35;
    } else {
        return 2;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.01;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerview = [[UIView alloc] init];
    headerview.backgroundColor = [UIColor colorWithRed:48 / 255.0 green:123 / 255.0 blue:225 / 255.0 alpha:1];
    
    if (section == 4 || section == 3) {
        UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 160, 20)];
        numLabel.text = [NSString stringWithFormat:@"共计%ld件商品", self.goodsInfoArrM.count];
        [headerview addSubview:numLabel];
        
        UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(WEITH - 88, 5, 80, 20)];
        priceLabel.textColor = [UIColor blackColor];
        priceLabel.font = [UIFont systemFontOfSize:14];
        priceLabel.text = [NSString stringWithFormat:@"¥%.2f", self.allPrice];
        
        
        
        if (section == 4) {
            
//            费率修改
            priceLabel.text = [NSString stringWithFormat:@"￥%.2f", self.allPrice + self.allRate + self.allYunFei];
//            self.Allprice.text = priceLabel.text;
        }
        
        [headerview addSubview:priceLabel];
        
        UILabel *otherLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(priceLabel.frame)-50, 5, 50, 20)];
        otherLabel.text = @"合计:  ";
        
        otherLabel.textAlignment = NSTextAlignmentRight;
        otherLabel.font = [UIFont systemFontOfSize:14];
        [headerview addSubview:otherLabel];

    }
    
    
    return headerview;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    return footview;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     [tableView endEditing:YES];
    if (indexPath.section == 0) {
        GetAddressViewController *getAddressVC = [[GetAddressViewController alloc] init];
        NSLog(@"%@",self.confirmDic);
        [self presentViewController:getAddressVC animated:YES completion:nil];
        
    }
    
}

//添加UI
- (void)addconfirmlastviewlUI {
    
    //底层的view
    UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0, HIGHT*0.93, (WEITH/3)*2, HIGHT*0.068)];
    firstView.backgroundColor = [UIColor whiteColor];
    firstView.layer.borderWidth = .6;
    firstView.layer.borderColor = [UIColor grayColor].CGColor;//[UIColor colorWithRed:244/255. green:244/255. blue:244/255. alpha:1].CGColor;
    [self.view addSubview:firstView];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake((WEITH/3)*2, HIGHT*0.93, WEITH/3, HIGHT*0.068);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [sureBtn addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    
    UILabel *translabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetWidth(firstView.frame)-60, 5, 60, CGRectGetHeight(firstView.frame)-10)];
    translabel.text = @"含运费";
    translabel.font = [UIFont systemFontOfSize:11];
    [firstView addSubview:translabel];
    
    self.Allprice = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(translabel.frame)-80, 5, 80, CGRectGetHeight(firstView.frame)-10)];
    self.Allprice.textColor = [UIColor redColor];
    self.Allprice.text = [NSString stringWithFormat:@"¥%.2f", self.allPrice + self.allRate + self.allYunFei];
    self.Allprice.textAlignment = NSTextAlignmentLeft;
    self.Allprice.font = [UIFont systemFontOfSize:12.5];
    [firstView addSubview:self.Allprice];
    
    UILabel *otherlabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.Allprice.frame)-60, 5, 60, CGRectGetHeight(firstView.frame)-10)];
    otherlabel.text = @"合计:  ";
    otherlabel.textAlignment = NSTextAlignmentRight;
    otherlabel.font = [UIFont systemFontOfSize:12.5];
    [firstView addSubview:otherlabel];
    
}

- (void)sureButtonClick{
    OrderPayViewController *orderpayVC = [[OrderPayViewController alloc] init];
    orderpayVC.jine = [NSString stringWithFormat:@"¥%.2f", self.allPrice + self.allRate + self.allYunFei];
    NSLog(@"%@",self.Allprice);
//    orderpayVC.address = self.addressDict;
    [self presentViewController:orderpayVC animated:YES completion:nil];
    
}



- (void)addgetaddressdatasources {
    
    AFHTTPRequestOperationManager *mgra = [AFHTTPRequestOperationManager manager];
    mgra.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    NSString *username = nameStr;
    
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", usernameStr]};
    
    [mgra POST:@"http://www.ylgw8.com/AppUser/Getdz" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        self.wholeAddArray  = [self toArrayOrNSDictionary:responseObject];
//
        [self.confirmtableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
    }];
}
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
- (void)getdata {
    // 获取当前账号
    NSDictionary *dic = [ReadLoginData readLoginData];
    if (dic.allKeys.count == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录,请登录后再次操作" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alview.tag = 123303;
        [alview show];
        
    }else {
        
        usernameStr = [dic[@"data"] objectForKey:@"username"];
        
    }
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 123303) {
        
        [self gobackClick];
    }else if (alertView.tag == 999) {
         ManagerViewController *mangerVC = [[ManagerViewController alloc] init];
        
        [self showViewController:mangerVC sender:nil];
        
    }else{
        
        NSLog(@"alert");
    }
 
}


@end
